package com.rephilo.sqlSession;

import com.rephilo.config.BoundSql;
import com.rephilo.pojo.Configuration;
import com.rephilo.pojo.MappedStatement;
import com.rephilo.utils.GenericTokenParser;
import com.rephilo.utils.ParameterMapping;
import com.rephilo.utils.ParameterMappingTokenHandler;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class SimpleExecutor implements Executor {
    @Override
    public <T> List<T> query(Configuration configuration, MappedStatement mappedStatement, Object... params) throws Exception {
        //注册驱动，获取连接
        PreparedStatement preparedStatement = getPreparedStatement(configuration, mappedStatement, params);

        //执行sql
        ResultSet resultSet = preparedStatement.executeQuery();

        String resultType = mappedStatement.getResultType();
        Class<?> resultTypeClass = getClassType(resultType);


        ArrayList<T> objects = new ArrayList<>();

        //封装返回结果集
        while (resultSet.next()) {
            T o = (T) resultTypeClass.newInstance();
            //元数据
            ResultSetMetaData metaData = resultSet.getMetaData();
            for (int i = 1; i <= metaData.getColumnCount(); i++) {
                //字段名
                String columnName = metaData.getColumnName(i);
                //字段值
                Object value = resultSet.getObject(columnName);
                //根据数据库表和实体的对应关系，完成封装
                if (containsFields(resultTypeClass, columnName)) {
                    PropertyDescriptor propertyDescriptor = new PropertyDescriptor(columnName, resultTypeClass);
                    Method writeMethod = propertyDescriptor.getWriteMethod();
                    writeMethod.invoke(o, value);
                }
            }

            objects.add(o);
        }

        return objects;
    }

    @Override
    public Integer update(Configuration configuration, MappedStatement mappedStatement, Object[] params) throws Exception {
        PreparedStatement preparedStatement = getPreparedStatement(configuration, mappedStatement, params);
        return preparedStatement.executeUpdate();
    }

    /**
     * 处理 PreparedStatement
     *
     * @param configuration
     * @param mappedStatement
     * @param param
     * @return
     * @throws SQLException
     * @throws ClassNotFoundException
     * @throws NoSuchFieldException
     * @throws IllegalAccessException
     */
    private PreparedStatement getPreparedStatement(Configuration configuration, MappedStatement mappedStatement, Object[] param) throws SQLException, ClassNotFoundException, NoSuchFieldException, IllegalAccessException {
        //注册驱动，获取连接
        Connection connection = configuration.getDataSource().getConnection();

        //获取sql语句
        String sql = mappedStatement.getSql();

        //转换sql语句
        BoundSql boundSql = getBoundSql(sql);

        //获取预处理对象 preparedStatement
        PreparedStatement preparedStatement = connection.prepareStatement(boundSql.getSqlText());

        //设置参数
        String parameterType = mappedStatement.getParameterType();
        Class<?> parameterTypeClass = getClassType(parameterType);

        List<ParameterMapping> parameterMappingList = boundSql.getParameterMappingList();
        for (int i = 0; i < parameterMappingList.size(); i++) {
            ParameterMapping parameterMapping = parameterMappingList.get(i);
            String content = parameterMapping.getContent();

            //反射
            Field declaredField = parameterTypeClass.getDeclaredField(content);
            //授权
            declaredField.setAccessible(true);
            Object o = declaredField.get(param[0]);

            preparedStatement.setObject(i + 1, o);
        }
        return preparedStatement;
    }

    private boolean containsFields(Class<?> resultTypeClass, String columnName) {
        long count = Arrays.stream(resultTypeClass.getDeclaredFields()).filter(x -> x.getName().equals(columnName)).count();
        return count > 0;
    }


    private Class<?> getClassType(String parameterType) throws ClassNotFoundException {
        if (parameterType != null) {
            return Class.forName(parameterType);
        }

        return null;
    }

    /**
     * 完成对#{}的解析工作
     * 将#{}使用？进行代替
     * 解析出#{}里面的值进行存储
     *
     * @param sql
     * @return
     */
    private BoundSql getBoundSql(String sql) {
        ParameterMappingTokenHandler parameterMappingTokenHandler = new ParameterMappingTokenHandler();
        GenericTokenParser tokenParser = new GenericTokenParser("#{", "}", parameterMappingTokenHandler);
        //解析后的sql
        String parsedSql = tokenParser.parse(sql);
        //#{}里解析出来的参数名称
        List<ParameterMapping> parameterMappings = parameterMappingTokenHandler.getParameterMappings();
        BoundSql boundSql = new BoundSql();
        boundSql.setSqlText(parsedSql);
        boundSql.setParameterMappingList(parameterMappings);

        return boundSql;
    }
}
